package com.jaychan.resource.server.com.jaychan.resource.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

/**
 * 作为资源服务的配置类必须满足两个条件，如下：
 *
 * 标注注解@EnableResourceServer
 * 继承ResourceServerConfigurerAdapter
 * @Author Jaychan tanjiecheng@borche.cn
 * @Date 2022/1/5 13:34
 */

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public RemoteTokenServices tokenServices(){
        //远程调用授权服务的check_token进行令牌的校验
        //由于认证中心使用的令牌存储策略是在内存中的
        //因此服务端必须远程调用认证中心的校验令牌端点/oauth/check_token 进行校验。
        RemoteTokenServices services = new RemoteTokenServices();

        //services.setCheckTokenEndpointUrl("http://localhost:9999/auth-server/oauth/check_token");

         //注意：远程校验令牌存在性能问题，
        //但是后续使用JWT令牌则本地即可进行校验，不必远程校验了
        services.setCheckTokenEndpointUrl("http://localhost:9999/oauth/check_token");

        //客户端的唯一id
        services.setClientId("jaychan");

        //客户端的秘钥
        services.setClientSecret("jaychan");
        return services;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //每个客户端有一个唯一的资源id，需要配置上
        resources.resourceId("res1")
                .tokenServices(tokenServices());
    }

    /**
     * 配置security的安全机制
     * 上文在认证中心的第6步配置客户端详情那里，
     * 有一行代码.scopes("all")则是指定了客户端的权限，
     * 资源服务可以根据这个scope进行url的拦截
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated();
    }
}
